package com.dreamer.repository.mobile;

import com.dreamer.domain.pmall.goods.PmallGoods;
import com.dreamer.domain.sub.SubGoods;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.*;
import org.springframework.stereotype.Repository;
import ps.mx.otter.utils.SearchParameter;

import java.util.List;

@Repository
public class SubGoodsDao extends BaseDaoImpl<SubGoods> {

    private Session getCurrentSession() {
        return getSessionFactory().getCurrentSession();
    }

    public List<SubGoods> findMallGoods(SearchParameter<SubGoods> p) {

        DetachedCriteria dc = DetachedCriteria.forClass(SubGoods.class);
        Example example = Example.create(p.getEntity()).enableLike(MatchMode.ANYWHERE);
        if(p.getEntity().getGoodsType()!=null&&p.getEntity().getGoodsType().getId()!=null){
            dc.add(Restrictions.eq("goodsType.id",p.getEntity().getGoodsType().getId()));
        }
        if(p.getEntity().getUser()!=null&&p.getEntity().getUser().getRealName()!=null&& !p.getEntity().getUser().getRealName().equals("")){
            DetachedCriteria user = dc.createCriteria("user");
            user.add(Restrictions.like("realName",p.getEntity().getUser().getRealName()));
        }
        if(p.getEntity().getUser()!=null&&p.getEntity().getUser().getAgentCode()!=null&& !p.getEntity().getUser().getAgentCode().equals("")){
            DetachedCriteria user = dc.createCriteria("user");
            user.add(Restrictions.eq("agentCode",p.getEntity().getUser().getAgentCode()));
        }
        dc.add(example);
        dc.addOrder(Order.desc("sequence"));
        return searchByPage(p,dc);
    }

    public List<SubGoods> findMallGoods_zh(SearchParameter<SubGoods> p) {
        DetachedCriteria dc = DetachedCriteria.forClass(SubGoods.class,"p");
        Example example = Example.create(p.getEntity()).enableLike(MatchMode.ANYWHERE);
        if(p.getEntity().getGoodsType()!=null&&p.getEntity().getGoodsType().getId()!=null){
            dc.add(Restrictions.eq("goodsType.id",p.getEntity().getGoodsType().getId()));
        }
        dc.add(example);
        dc.add(Restrictions.eq("p.canAdvance",true));
        dc.addOrder(Order.asc("p.sort"));
        return searchByPage(p,dc);
    }

    public List<SubGoods> findMallGoodss_zh() {
        String hql = "from SubGoods as l where l.canAdvance=1  ORDER BY l.sort ASC";
        Query query = getCurrentSession().createQuery(hql);
        return query.list();
    }

    public List<PmallGoods> findSubGoodsBUserId(Integer userId) {
        String hql = "from PmallGoods sg where sg.user.id = :userId and sg.subGoods='置换商城' ";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("userId",userId);
        return query.list();
    }

}


